<template>
	<view class="page">
		<!-- 顶部栏 -->
		<view class="header">
			<view class="header-left">
				<image class="logo" src="../../static/logo.png" />
				<text class="shop-name">{{$store.state.app.userInfo.deliveryPersonnelName || '洪湖门店'}}</text>
			</view>
			<view class="header-right">
				<image src="../../static/logout.png" alt="" style="width: 50rpx; height: 50rpx;"
					@click="handleLogout" />
			</view>
		</view>

		<!-- 菜单区 -->
		<view class="menu-list">
			<view class="menu-item" v-for="(item,index) in getMenuListType" :key="index">
				<view class="dot" v-if="item.count>0">{{ item.count }}</view>
				<view class="menu-icon-bg" @click="jumpPage(item)">
					<image :src="item.imgSrc" style="width: 60rpx; height: 60rpx;" />
				</view>
				<text class="menu-title">{{item.title}}</text>
			</view>
		</view>

		<!-- 消息提醒区 -->
		<view class="message-section">
			<view class="tabs">
				<view class="tab" v-for="(tab, index) in tabs" :key="index" :class="{active: index === activeTab}"
					@click="change(tab.value, index)">{{tab.name}}</view>
			</view>
			<view class="message-list">
				<view class="message-item flex-between flex-column" v-for="(item, index) in list" :key="index" @click="navigate(item)">
					<view class="w100 flex-between ">
						<view class="flex">
							<text style="color: #1D2129; font-weight: 600; font-size: 30rpx;">{{item.title}}</text>
							<view class="dot" v-if="!item.isRead"></view>
						</view>
						<text style="color: #9AA3AE; font-size: 24rpx;">{{item.createTime}}</text>
					</view>
					<view class="w100 flex-between align-center margin20">
						<text style="color: #4E5969; font-size: 28rpx;">{{item.content}}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		// personnelSendLoc, // 已注释，避免iOS审核问题
		getMsgList,
		getInfo,
		read
	} from '@/api/index.js'
	export default {
		data() {
			return {
				title: 'Hello',
				lastSendTime: 0, // 记录上次发送时间
				isRefreshing: false, // 是否正在刷新
				// loginType 1 骑手 2门店
				menuList: [
					// 骑手订单管理
					{
						title: '订单管理',
						lable: 'orderManageRider',
						imgSrc: require('../../static/' + 'orderManage' + '.png'),
						loginType: [1],
						count: 0,
					},
					{
						title: '订单管理',
						lable: 'orderManage',
						imgSrc: require('../../static/' + 'orderManage' + '.png'),
						loginType: [2],
						count: 0,
					}, {
						title: '商品入库',
						lable: 'orderIn',
						imgSrc: require('../../static/' + 'orderIn' + '.png'),
						loginType: [2],
						count: 0,
					},
					{
						title: '商品出库',
						lable: 'orderOut',
						imgSrc: require('../../static/' + 'orderOut' + '.png'),
						loginType: [2],
						count: 0,
					},
					// {
					// 	title: '订单调整',
					// 	lable: 'orderChange',
					// 	imgSrc: require('../../static/' + 'orderChange' + '.png'),
					// 	loginType: [1, 2]
					// },
					{
						title: '商品盘点',
						lable: 'inventory',
						imgSrc: require('../../static/' + 'inventory' + '.png'),
						loginType: [2],
						count: 0,
					},
					{
						title: '商品管理',
						lable: 'productManage',
						imgSrc: require('../../static/' + 'productManage' + '.png'),
						loginType: [2],
						count: 0,
					},
					{
						title: '订单核销',
						lable: 'orderCancel',
						imgSrc: require('../../static/' + 'orderCancel' + '.png'),
						loginType: [2],
						count: 0,
					},
					{
						title: '取货',
						lable: 'pickUp',
						imgSrc: require('../../static/' + 'pickUp' + '.png'),
						loginType: [1],
						count: 0,
					},
					{
						title: '售后管理',
						lable: 'afterSales',
						imgSrc: require('../../static/' + 'orderChange' + '.png'),
						loginType: [2],
						count: 0,
					},
					{
						title: '店铺统计',
						lable: 'statistique',
						imgSrc: require('../../static/' + 'statistique' + '.png'),
						loginType: [2],
						count: 0,
					},
				],
				tabs: [{
					name: "全部",
					value: "all"
				}, {
					name: "入库",
					value: "in"
				}, {
					name: "出库",
					value: "out"
				}, 
				{
					name: "订单",
					value: "order"
				},
				{
					name: "售后",
					value: "refundOrder"
				},
				],
				type: "all",
				limit: 10,
				page: 1,
				isLastPage: false,
				activeTab: 0,
				list: [],

			}
		},
		computed: {
			getMenuListType() {
				return this.menuList.filter(item => item.loginType.includes(this.$store.state.app.userInfo.loginType))
			},
		},
		
		onShow() {
			this.page = 1
			this.list = []
			this.getList()
			this.getInfoFun()
		},
		
		onReachBottom() {
			if(this.isLastPage) return
			this.page++
			this.getList() 
		},
		onPullDownRefresh(){
			this.page = 1
			this.list = []
			this.isLastPage = false
			this.getList().finally(()=>{
				uni.stopPullDownRefresh();
			})
		},
		async onReady() {
			// 注释掉持久位置跟踪功能，避免iOS审核问题
			// return
			// const throttledSendLocation = this.throttle(this.sendLocationToServer, 10000);
			// let a = function(locationData) {
			// 	console.log(uni.getStorageSync('LIn97112479'), 110);
			// 	throttledSendLocation(locationData);
			// }
			// let b = function(err) {
			// 	uni.showModal({
			// 		title: '提示',
			// 		content: JSON.stringify(err)
			// 	})
			// }
			// if (this.$store.state.app.userInfo.loginType == 1) {
			// 	await this.$store.dispatch('getPositonStatus', '')
			// }
			// console.log(this.$store.state.app.isSendPosition, this.$store.state.app.userInfo.loginType == 1);
			// if (this.$store.state.app.isSendPosition && this.$store.state.app.userInfo.loginType == 1) {
			// 	getLocations({
			// 		provider: "system",
			// 		geocode: false,
			// 		fun: a,
			// 		err: b,
			// 		time: 10000
			// 	})

			// }
		},

		methods: {
			change(value, index){
				this.activeTab = index
				this.type = value
				this.page = 1
				this.list = []
				this.getList()
			},
			
			getInfoFun(){
				getInfo().then(res=>{
					console.log(res)
					let info = res.data
					this.menuList= [
						{
							title: '订单管理',
							lable: 'orderManageRider',
							imgSrc: require('../../static/' + 'orderManage' + '.png'),
							loginType: [1],
							count: info.pendingShipmentCount + info.pendingStockedCount,
						},
						{
							title: '订单管理',
							lable: 'orderManage',
							imgSrc: require('../../static/' + 'orderManage' + '.png'),
							loginType: [2],
							count: info.pendingShipmentCount + info.pendingStockedCount,
						}, {
							title: '商品入库',
							lable: 'orderIn',
							imgSrc: require('../../static/' + 'orderIn' + '.png'),
							loginType: [2],
							count: info.pendingInCount,
						},
						{
							title: '商品出库',
							lable: 'orderOut',
							imgSrc: require('../../static/' + 'orderOut' + '.png'),
							loginType: [2],
							count: info.pendingOutCount,
						},
						// {
						// 	title: '订单调整',
						// 	lable: 'orderChange',
						// 	imgSrc: require('../../static/' + 'orderChange' + '.png'),
						// 	loginType: [1, 2]
						// },
						{
							title: '商品盘点',
							lable: 'inventory',
							imgSrc: require('../../static/' + 'inventory' + '.png'),
							loginType: [2],
							count: info.pendingStocktakingCount,
						},
						{
							title: '商品管理',
							lable: 'productManage',
							imgSrc: require('../../static/' + 'productManage' + '.png'),
							loginType: [2],
							count: 0,
						},
						{
							title: '订单核销',
							lable: 'orderCancel',
							imgSrc: require('../../static/' + 'orderCancel' + '.png'),
							loginType: [2],
							count: 0,
						},
						{
							title: '取货',
							lable: 'pickUp',
							imgSrc: require('../../static/' + 'pickUp' + '.png'),
							loginType: [1],
							count: 0,
						},
						{
							title: '售后管理',
							lable: 'afterSales',
							imgSrc: require('../../static/' + 'orderChange' + '.png'),
							loginType: [2],
							count: info.pendingDoorstepCount,
						},
						{
							title: '店铺统计',
							lable: 'statistique',
							imgSrc: require('../../static/' + 'statistique' + '.png'),
							loginType: [2],
							count: 0,
						},
					]
				})
			},
			
			navigate(item){
				let path = ""
				console.log(item.id)
				read(item.id).then(res=>{})
				if(item.type===33) path = `/pages/orderIn/detail?id=${item.linkId}&inOrOutWarehouseType=2` //1:出 2:入
				if(item.type===34) path = `/pages/orderIn/detail?id=${item.linkId}&inOrOutWarehouseType=1` //1:出 2:入
				if(item.type===9 || item.type===10 || item.type===11 || item.type===23) path = '/pages/orderDetails/orderDetails?orderNo=' + item.linkId
				if(item.type===14 || item.type===15 || item.type===16) path = '/pages/returnDetails/returnDetails?refundOrderNo=' + item.linkId
				uni.navigateTo({
					url: path
				})
			},
			
			getList(){
				return new Promise((resolve, reject) => {
				getMsgList({
					groupType: this.type,
					limit: this.limit,
					page: this.page
				}).then(res=>{
					console.log(res)
					this.list = this.list.concat(res.data.list)
					this.isLastPage = this.page === res.data.totalPage
					resolve(res)
				}).catch(err=>{
						reject(err)
					})
				})
			},
			// 退出登录
			handleLogout() {
				uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							// clearLocations()
							uni.clearStorage()
							// 清除token
							uni.removeStorageSync('token');
							// 清除用户信息
							uni.removeStorageSync('userInfo');
							// 清除位置信息
							uni.removeStorageSync('LIn97112479');
							uni.removeStorageSync('ISSEND_POSITION');
							// 返回登录页
							uni.reLaunch({
								url: '/pages/login/login'
							});
						}
					}
				});
			},

			// 节流函数 - 已注释，避免iOS审核问题
			// throttle(func, delay) {
			// 	return (...args) => {
			// 		const now = Date.now();
			// 		if (now - this.lastSendTime >= delay) {
			// 			this.lastSendTime = now;
			// 			func.apply(this, args);
			// 		}
			// 	}
			// },

			// 发送位置到后台 - 已注释，避免iOS审核问题
			// sendLocationToServer(locationData = JSON.parse(uni.getStorageSync('LIn97112479'))) {
			// 	console.log(locationData);
			// 	if (locationData && locationData.coords) {
			// 		const {
			// 			longitude,
			// 			latitude
			// 		} = locationData.coords;

			// 		// 将WGS84坐标转换为GCJ02坐标
			// 		const gcj02 = this.wgs84ToGcj02(latitude, longitude);
			// 		const locationStr = gcj02.latitude + ',' + gcj02.longitude;

			// 		console.log('发送位置数据到后台:', {
			// 			original: {
			// 				longitude,
			// 				latitude
			// 			},
			// 			converted: gcj02,
			// 			locationStr
			// 		});

			// 		// 生成日志
			// 		const logData = {
			// 			time: new Date().toLocaleString(),
			// 			location: locationStr,
			// 			status: 'sending'
			// 		};
			// 		console.log('发送位置日志:', logData);

			// 		// 调用API发送位置数据
			// 		personnelSendLoc({
			// 			location: locationStr
			// 		}).then(res => {
			// 			console.log('位置发送成功:', res);
			// 			// 更新日志状态
			// 			const successLog = {
			// 				...logData,
			// 				status: 'success',
			// 				response: res
			// 			};
			// 			console.log('位置发送成功日志:', successLog);
			// 		}).catch(err => {
			// 			console.error('位置发送失败:', err);
			// 			// 更新日志状态
			// 			const errorLog = {
			// 				...logData,
			// 				status: 'failed',
			// 				error: err
			// 			};
			// 			console.log('位置发送失败日志:', errorLog);
			// 		});
			// 	}
			// },

			// WGS84转GCJ02坐标 - 已注释，避免iOS审核问题
			// wgs84ToGcj02(lat, lng) {
			// 	const a = 6378245.0; // 长半轴
			// 	const ee = 0.00669342162296594323; // 偏心率平方
			// 	const pi = 3.1415926535897932384626; // 圆周率

			// 	if (this.outOfChina(lat, lng)) {
			// 		return {
			// 			latitude: lat,
			// 			longitude: lng
			// 		};
			// 	}

			// 	let dLat = this.transformLat(lng - 105.0, lat - 35.0);
			// 	let dLng = this.transformLng(lng - 105.0, lat - 35.0);
			// 	const radLat = lat / 180.0 * pi;
			// 	let magic = Math.sin(radLat);
			// 	magic = 1 - ee * magic * magic;
			// 	const sqrtMagic = Math.sqrt(magic);
			// 	dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
			// 	dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);

			// 	// 添加微调参数
			// 	const adjustLat = 0.0000001;
			// 	const adjustLng = 0.0000001;

			// 	return {
			// 		latitude: Number((lat + dLat + adjustLat).toFixed(7)),
			// 		longitude: Number((lng + dLng + adjustLng).toFixed(7))
			// 	};
			// },

			// 判断是否在中国境内 - 已注释，避免iOS审核问题
			// outOfChina(lat, lng) {
			// 	return (lng < 72.004 || lng > 137.8347) || (lat < 0.8293 || lat > 55.8271);
			// },

			// 纬度转换 - 已注释，避免iOS审核问题
			// transformLat(x, y) {
			// 	const pi = 3.1415926535897932384626;
			// 	let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
			// 	ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
			// 	ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0;
			// 	ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0;
			// 	return ret;
			// },

			// 经度转换 - 已注释，避免iOS审核问题
			// transformLng(x, y) {
			// 	const pi = 3.1415926535897932384626;
			// 	let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
			// 	ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
			// 	ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0;
			// 	ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0;
			// 	return ret;
			// },

			jumpPage(item) {
				console.log(67, item);
				uni.navigateTo({
					url: '/pages/' + item.lable + '/' + item.lable
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background: #f7f8fa;
		position: relative;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 80rpx 40rpx 30rpx 40rpx;
		background: #fff;

		.logo {
			width: 60rpx;
			height: 60rpx;
			margin-right: 24rpx;
		}

		.shop-name {
			font-size: 32rpx;
			font-weight: bold;
			margin-right: 40rpx;
		}

		.search-bar {
			flex: 1;
			display: flex;
			align-items: center;
			background: #f2f3f5;
			border-radius: 32rpx;
			padding: 0 20rpx;

			.search-input {
				flex: 1;
				border: none;
				background: transparent;
				font-size: 28rpx;
				padding: 16rpx 0;
			}

			.search-icon {
				width: 32rpx;
				height: 32rpx;
			}
		}
	}

	.menu-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: flex-start;
		background: #fff;
		margin: 32rpx 40rpx 0 40rpx;
		border-radius: 16rpx;
		padding: 32rpx 0;

		.menu-item {
			width: 160rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-bottom: 32rpx;
			position: relative;
			.dot {
				width: 38rpx;
				height: 38rpx;
				border-radius: 50%;
				background: #E34D59;
				text-align: center;
				line-height: 38rpx;
				color: #fff;
				position: absolute;
				right: 0;
				top: 0;
				font-size: 20rpx;
			}
			.menu-icon-bg {
				width: 120rpx;
				height: 120rpx;
				background: #f2f3f5;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 16rpx;
			}

			.menu-title {
				font-size: 28rpx;
				color: #333;
				text-align: center;
			}
		}
	}

	.message-section {
		// 
		margin: 0 40rpx 0 40rpx;
		border-radius: 16rpx;
		padding: 32rpx 0 0 0;

		.tabs {
			display: flex;
			margin-bottom: 24rpx;
			padding: 30rpx;
			background: #fff;
			.tab {
				padding: 12rpx 32rpx;
				font-size: 28rpx;
				color: #666;
				border-radius: 32rpx;
				margin-right: 16rpx;
				background: #f2f3f5;

				&.active {
					background: #1890ff;
					color: #fff;
				}
			}
		}

		.message-list {
			width: 100%;
			.message-item {
				width: 100%;
				background: #f7f8fa;
				border-radius: 8rpx;
				padding: 24rpx 32rpx;
				margin-bottom: 16rpx;
				background: #fff;
				margin-top: 30rpx;
				.dot {
					width: 16rpx;
					height: 16rpx;
					left: 0;
					top: 0;
					background: #E34D59;
					border-radius: 50%;
				}
			}
		}
	}

	.logout-btn {
		position: fixed;
		right: 60rpx;
		bottom: 60rpx;
		display: flex;
		align-items: center;
		gap: 20rpx;
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
		padding: 16rpx 32rpx;

		.userName {
			font-size: 28rpx;
			color: #333;
		}
	}
</style>